package com.risk.ctrl.config.okhttp;

import cn.hutool.core.util.BooleanUtil;
import com.risk.ctrl.config.okhttp.interceptor.HeaderInterceptor;
import com.risk.ctrl.config.okhttp.property.OkhttpProperty;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableConfigurationProperties(OkhttpProperty.class)
public class OkhttpConfig {
    /**
     * 创建并配置 OkHttpClient Bean
     * @return 配置好的 OkHttpClient 实例
     */
    @Bean
    public OkHttpClient okHttpClient(OkhttpProperty okhttpProperty, HeaderInterceptor headerInterceptor) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                // 连接超时
                .connectTimeout(okhttpProperty.getConnectTimeOut(), TimeUnit.SECONDS)
                // 读取超时
                .readTimeout(okhttpProperty.getReadTimeOut(), TimeUnit.SECONDS)
                // 写入超时
                .writeTimeout(okhttpProperty.getWriteTimeOut(), TimeUnit.SECONDS)
                // 重试
                .retryOnConnectionFailure(true)
                // 可以添加其他拦截器，如 Header 添加、Token 刷新等
                .addInterceptor(headerInterceptor)
                .build();
        // 日志拦截器（开发环境推荐开启，生产环境可关闭或调整级别）
        if(BooleanUtil.isTrue(okhttpProperty.getEnableLog())){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClient = new OkHttpClient.Builder()
                    // 连接超时
                    .connectTimeout(okhttpProperty.getConnectTimeOut(), TimeUnit.SECONDS)
                    // 读取超时
                    .readTimeout(okhttpProperty.getReadTimeOut(), TimeUnit.SECONDS)
                    // 写入超时
                    .writeTimeout(okhttpProperty.getWriteTimeOut(), TimeUnit.SECONDS)
                    // 重试
                    .retryOnConnectionFailure(true)
                    // 可以添加其他拦截器，如 Header 添加、Token 刷新等
                    .addInterceptor(headerInterceptor)
                    .addInterceptor(loggingInterceptor)
                    .build();
        }
        return okHttpClient;
    }
}
